<template>
  <el-dialog v-dialogDrag :visible.sync="dialogVisible" :title="title" width="1000px" @close="resetForm('ruleForm')">
    <button-group ref="buttonGroup" @submitForm="submitForm('ruleForm')" @cancel="dialogVisible = false" />
    <div class="formTopFont">生产计划单</div>
    <el-row>
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="auto">
        <el-row>
          <el-col :span="8">
            <el-form-item label="计划单号" prop="planNo">
              <el-input v-model="ruleForm.planNo" maxlength="20" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="销售单号" prop="saleId">
              <el-input v-model="ruleForm.saleNo" v-if="this.title === '编辑'" disabled show-word-limit />
              <el-select v-model="ruleForm.saleId" v-else @change="getSaleDetail(ruleForm.saleId)" style="width: 100%" filterable>
                <el-option v-for="item in getSaleList" :key="item.id" :label="item.saleNo" :value="item.id">
                  <span style="float: left">{{ item.saleNo }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="生产批号" prop="proNo">
              <el-input v-model="ruleForm.proNo" maxlength="20" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="计划开始时间" prop="planBeginDate">
              <el-date-picker v-model="ruleForm.planBeginDate" type="date" placeholder="选择日期时间" style="width: 100%" format="yyyy-MM-dd" value-format="yyyy-MM-dd" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="计划结束时间" prop="planEndDate">
              <el-date-picker v-model="ruleForm.planEndDate" type="date" placeholder="选择日期时间" style="width: 100%" format="yyyy-MM-dd" value-format="yyyy-MM-dd" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="录入时间" prop="enterAt">
              <el-date-picker v-model="ruleForm.enterAt" type="datetime" placeholder="选择日期时间" style="width: 100%" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="录入人" prop="enterBy">
              <el-select v-model="ruleForm.enterBy" style="width: 100%" filterable>
                <el-option v-for="item in userAllList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="计划类别" prop="type">
              <el-select v-model="ruleForm.type" style="width: 100%" filterable>
                <el-option label="订单" value="订单"></el-option>
                <el-option label="备库" value="备库"></el-option>
                <el-option label="其他" value="其他"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="ruleForm.remark" type="textarea" rows="3" maxlength="500" show-word-limit />
        </el-form-item>
      </el-form>
      <el-table border class="tabOver" stripe height="220px" :data="ruleForm.materials">
        <el-table-column prop="materialId" align="center">
          <template slot="header">
            <span style="color: #f56c6c">*</span>物料
          </template>
          <template #default="{ row, $index }">
            <!-- 展示物料名称-物料编号-规格-单位 -->
            <el-select v-model="row.materialId" :disabled="ruleForm.disabled" size="mini" style="width: 100%" filterable @change="selectWhseList(row, $index)">
              <el-option v-for="item in materialAll" :key="item.id" :value="item.id" :label="
                  item.materialName +
                  `${
                    item.materialCode !== ''
                      ? '-【' + item.materialCode + '】'
                      : ''
                  }`
                " />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="unit" label="单位" width="100px" align="center" />
        <el-table-column prop="deliveryDate" align="center" width="185px">
          <template slot="header">
            <span style="color: #f56c6c">*</span>计划交期
          </template>
          <template #default="{ row }">
            <el-date-picker v-model="row.deliveryDate" size="mini" type="datetime" format="yyyy-MM-dd" value-format="yyyy-MM-dd" placeholder="选择日期时间"></el-date-picker>
          </template>
        </el-table-column>
        <el-table-column prop="saleNum" align="center" width="100px">
          <template slot="header">
            <span style="color: #f56c6c">*</span>订单数量
          </template>
          <template #default="{ row }">
            <el-input-number v-model="row.saleNum" size="mini" :disabled="ruleForm.disabled" :controls="false" :min="0" style="width: 100%" />
          </template>
        </el-table-column>
        <el-table-column prop="planNum" align="center" width="100px">
          <template slot="header">
            <span style="color: #f56c6c">*</span>计划数量
          </template>
          <template #default="{ row }">
            <el-input-number v-model="row.planNum" size="mini" :controls="false" :min="1" style="width: 100%" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100px" align="center">
          <template #default="{ $index }">
            <el-button type="danger" icon="el-icon-delete" v-if="!ruleForm.saleId" @click="ruleForm.materials.splice($index, 1)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button style="width: 100%" @click="ruleForm.materials.push({ ...basicParams })" v-if="!ruleForm.saleId">添加</el-button>
    </el-row>
    <bottom-font v-if="title === '编辑'" ref="bottomFont" :obj-name="ruleForm.enterName ? ruleForm.enterName : this.$store.getters.compInfo.userName" :obj-date="ruleForm.createAt" />
  </el-dialog>
</template>
<script>
import bottomFont from '@/components/BottomFont'
export default {
  components: { bottomFont },
  props: {
    userAllList: {
      type: Array,
      default: () => {
        return []
      }
    },
    materialAll: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data() {
    const checkPlanNo = async (rule, value, callback) => {
      const res = await this.$axios.get(
        `/sale/order/verifyNoUnique?no=${value}&id=${this.ruleForm.id || ''}`
      )
      if (res?.data.code === 200) {
        return res.data.data
          ? callback()
          : new Error(callback('计划单号重复！'))
      } else {
        return new Error(callback(res.data.msg))
      }
    }
    const params = {
      deliveryDate: '',
      materialId: '',
      saleNum: '',
      unit: ''
    }
    return {
      title: '',
      ruleForm: {
        planNo: '',
        proNo: '',
        planBeginDate: '',
        planEndDate: '',
        status: '',
        type: '',
        enterAt: '',
        enterBy: '',
        remark: '',
        materials: [],
        saleId: '',
        disabled: true
      },
      rules: {
        materialId: [
          { required: true, message: '物料不能不能为空！', trigger: 'change' }
        ],
        planNo: [
          { required: true, message: '计划单号不能为空！', trigger: 'blur' },
          { validator: checkPlanNo, trigger: 'blur' }
        ],
        procedureId: [
          { required: true, message: '工序不能不能为空！', trigger: 'change' }
        ]
      },
      dialogVisible: false,
      getSaleList: [],
      basicParams: params
    }
  },
  watch: {
    ruleForm: {
      deep: true,
      handler(row) {
        if (!row.saleId) {
          row.disabled = false
        } else {
          row.disabled = true
        }
      }
    }
  },
  mounted() {},
  methods: {
    /**
     * @description: 新增编辑
     * @param {*} row
     * @return {*}
     */
    async showDialog(row) {
      this.getSale()
      if (row && row.hasOwnProperty('id')) {
        this.title = '编辑'
        this.getDetail(row.id)
      } else {
        this.title = '新增'
      }
      this.dialogVisible = true
    },
    /* 编辑获取详情 */
    async getDetail(id) {
      const res = await this.$axios.get(`/pro/plan/getDetail?id=${id}`)
      if (res.data.code === 200) {
        this.ruleForm = { ...this.ruleForm, ...res.data.data }
      }
    },
    /* 新增：获取未下达的订单 */
    async getSale() {
      const res = await this.$axios.get(`/pro/plan/getSale`)
      if (res.data.code === 200) {
        this.getSaleList = res.data.data
      }
    },
    /* 新增：获取未下达的订单的详情 */
    async getSaleDetail(id) {
      const res = await this.$axios.get(`/pro/plan/getSaleDetail?id=${id}`)
      if (res.data.code === 200) {
        this.ruleForm.materials = res.data.data
      }
    },
    /* 物料选择 */
    selectWhseList(row, index) {
      row.num = ''
      row.unit = ''
      const { unit, num } = this.materialAll.find(
        (item) => item.id === row.materialId
      )
      row.unit = unit
      row.saleNum = num
    },
    /**
     * @description: 表单提交
     * @param {*} formName
     * @return {*}
     */
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          const res = await this.$axios.post('/pro/plan/save', this.ruleForm)
          if (res?.data.code === 200) {
            this.$notify.success('提交成功！')
            this.dialogVisible = false
            this.$emit('getTableInfo')
          } else {
            this.$notify.error(res.data.msg)
          }
        }
      })
    },
    /**
     * @description: 重置表单
     * @param {*} formName
     * @return {*}
     */
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.ruleForm = {
        planNo: '',
        proNo: '',
        planBeginDate: '',
        planEndDate: '',
        status: '',
        type: '',
        enterAt: '',
        enterBy: '',
        remark: '',
        materials: [],
        saleId: '',
        disabled: null
      }
    }
  }
}
</script>
<style lang='scss' scoped>
</style>
